#from myelin.Ns import MYELINS
from nodetypes.formats.mml.Events import EventHandler
from nodetypes.services.sparql.UrlService import Service as SparqlService
from nodetypes.services.RdfQueryConfig import Serializer as ConfigSerializer

from myelin.server.lib.http import Status
import amara

from forms import Commit, \
    SearchResults


class EventHandler(EventHandler):
    
    # searcher
    newSparqlService        = SparqlService
    newConfigSerializer     = ConfigSerializer
   
    # event forms
    newCommitForm           = Commit.Form
    newSearchResultsForm    = SearchResults.Form
    
    def process(self, context, source):
        eventData = context.event.data            
        eventData.config = self.newConfigSerializer().deserialize(source.asInputSource())
        if self.newSparqlService().execute(context, source):
            eventData.status = u'success'
            eventData.status_type = u'sparql-success'
            eventData.form = self.newSearchResultsForm()
            
            eventData.stage = 1
            eventData.submits = context.transform.submitEvents[1]
            
        else:            
            eventData.status = u'failure'
            eventData.status_type = u'search-param-errors'
            eventData.form = self.newCommitForm()
            
            eventData.stage = 0
            eventData.submits = context.transform.submitEvents[0]
            
            context.request.status = Status.HTTP_BAD_REQUEST
            
        context.model = context.nodeType.retrieveModel(context)
        
        return self.newDocument().createDocument(context, source)